#include "Character.h"

Character::Character(QObject *parent)
    : GameObject(parent)
{}

void Character::move(float dx, float dy)
{
    setPos(pos() + QPointF(dx, dy));
}

//动画相关

void Character::setAnimationFrames(Direction dir, const QVector<QPixmap> &frames)
{
    m_animations[dir] = frames; // 若不存在键为 dir 的项，会自动插入一个新的项，其键为dir
    if (dir == m_currentDirection && !frames.isEmpty()) { //设置第一帧（默认向下）
        setPixmap(frames.first());
        initializeCollisionShape(); //初始化形状，派生类调用对应的函数
    }
}

void Character::setCurrentDirection(Direction dir, bool is_resetFrames)
{
    if (m_currentDirection == dir)
        return;
    m_currentDirection = dir;

    if (is_resetFrames) { //转向重置
        m_currentFrame = 0;
        m_frameTimer = 0.0f;
    }

    if (m_animations.contains(dir) && !m_animations[dir].isEmpty()) {
        setPixmap(m_animations[dir].first());
    }
}

void Character::updateAnimation(float deltaTime)
{
    if (!m_animations.contains(m_currentDirection))
        return;

    const QVector<QPixmap> &frames = m_animations[m_currentDirection];
    if (frames.isEmpty() || frames.size() == 1)
        return;

    m_frameTimer += deltaTime;

    // 检查是否需要切换到下一帧
    if (m_frameTimer >= FRAME_DURATION) {
        m_frameTimer = 0.0f;
        m_currentFrame = (m_currentFrame + 1) % frames.size();
        setPixmap(frames[m_currentFrame]);
    }
}

void Character::initializeCollisionShape()
{
    setCollisionShapeMode(QGraphicsPixmapItem::BoundingRectShape);
}

void Character::update(float deltaTime)
{
    // 更新动画
    updateAnimation(deltaTime);
}
